import axios from 'axios'
import lodash from 'lodash'
import pathToRegexp from 'path-to-regexp'
import { message } from 'antd'
import {baseURL} from './config'
import qs from 'qs'
import jsonp from 'jsonp'

axios.defaults.baseURL = baseURL
axios.defaults.headers={
  'Content-Type' : 'application/json;charset=utf-8',
  'access-token' : localStorage.getItem('access_token') || '',
};
const fetch = (url,options) => {
  let {
    method = 'get',
    data,
  } = options
  const cloneData = lodash.cloneDeep(data)

  if(url.match('http')){
    return  new Promise((resolve, reject) => {
      jsonp(url, {
        param: `${qs.stringify(cloneData)}&callback`,
        name: `jsonp_${new Date().getTime()}`,
        timeout: 4000,
      }, (error, result) => {
        if (error) {
          reject(error)
        }
        resolve({ status: 200, data: result })
      })
    })
  }

  switch (method.toLowerCase()) {
    case 'get':
      return axios.get(url, {
        params: cloneData,
      })
    case 'delete':
      return axios.delete(url, {
        data: cloneData,
      })
    case 'post':
      return axios.post(url, cloneData)
    case 'put':
      return axios.put(url, cloneData)
    case 'patch':
      return axios.patch(url, cloneData)
    default:
      return axios(options)
  }
}

function checkStatus(res) {
  if (res.status >= 200 && res.status < 300) {
    return res
  }else if(res.status===401){
    window.location= `${location.origin}/login`;
  }
}

function handelData(res) {
  //获取消息头中的token
  const token = res.headers['access-token'];
  // 将消息头中的token存入localStorage
  if (token) {
    localStorage.setItem('access_token',token);
  }
  const data = res.data;
  try {
    if(typeof(data)==='string'){
      return JSON.parse(data);
    }
  } catch (e) {
    console.log('json解析错误：',e);
  }

  return data;
}

function handleError(error) {
  message.error('加载数据失败了，请重试！',3)
  console.log('error:',error);
}

export default function request (url,options) {
  return fetch(url, options)
        .then(checkStatus)
        .then(handelData)
        .catch(handleError)
}
